<template>
  <div id="mapView" class="map-view">
    <!-- 左侧事故列表面板 -->
    <div class="accident-panel" :class="{ 'collapsed': isPanelCollapsed }">
      <div class="collapse-button" @click="togglePanel">
        <el-icon :size="20">
          <ArrowLeft v-if="!isPanelCollapsed" />
          <ArrowRight v-else />
        </el-icon>
      </div>
      <el-card class="accident-card" v-show="!isPanelCollapsed">
        <template #header>
          <div class="card-header">
            <h3>事故处理中心</h3>
            <p class="subtitle">您可以查看和处理上报的事故</p>
          </div>
        </template>

        <!-- 筛选工具栏 -->
        <div class="filter-toolbar">
          <el-select
            v-model="filterStatus"
            placeholder="处理状态"
            clearable
            style="width: 120px; margin-right: 10px"
          >
            <el-option label="未处理" value="未处理"></el-option>
            <el-option label="处理中" value="处理中"></el-option>
            <el-option label="已处理" value="已处理"></el-option>
          </el-select>
          <el-select
            v-model="filterSeverity"
            placeholder="严重程度"
            clearable
            style="width: 120px; margin-right: 10px"
          >
            <el-option label="轻微" value="轻微"></el-option>
            <el-option label="一般" value="一般"></el-option>
            <el-option label="严重" value="严重"></el-option>
            <el-option label="特别严重" value="特别严重"></el-option>
          </el-select>
          <el-button type="primary" @click="refreshAccidentList">
            <el-icon><Refresh /></el-icon>
          </el-button>
        </div>

        <!-- 事故列表 -->
        <el-table
          :data="accidents"
          style="width: 100%"
          height="calc(100vh - 250px)"
          @row-click="handleAccidentClick"
          v-loading="loading"
          :key="refreshKey"
        >
          <el-table-column prop="accident_type" label="事故类型" width="100"></el-table-column>
          <el-table-column prop="severity" label="严重程度" width="100">
            <template #default="{ row }">
              <el-tag :type="getSeverityType(row.severity)" effect="dark">
                {{ row.severity }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="date_time" label="发生时间" width="180"></el-table-column>
          <el-table-column prop="status" label="处理状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" effect="plain">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                @click.stop="openHandleDialog(row)"
                :disabled="row.status === '已处理'"
              >
                处理
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 事故处理对话框 -->
    <el-dialog
      v-model="handleDialogVisible"
      title="事故处理"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="handleForm" label-width="120px" :rules="handleFormRules" ref="handleFormRef">
        <el-form-item label="事故ID" prop="accident_id">
          <el-input v-model="handleForm.accident_id" disabled></el-input>
        </el-form-item>
        <el-form-item label="事故类型" prop="accident_type">
          <el-input v-model="handleForm.accident_type" disabled></el-input>
        </el-form-item>
        <el-form-item label="严重程度" prop="severity">
          <el-input v-model="handleForm.severity" disabled></el-input>
        </el-form-item>
        <el-form-item label="发生时间" prop="date_time">
          <el-input v-model="handleForm.date_time" disabled></el-input>
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="handleForm.status" placeholder="请选择处理状态" style="width: 100%">
            <el-option label="未处理" value="未处理"></el-option>
            <el-option label="处理中" value="处理中"></el-option>
            <el-option label="已处理" value="已处理"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理信息" prop="HandleMessage">
          <el-input
            v-model="handleForm.HandleMessage"
            type="textarea"
            placeholder="请输入处理信息"
            :rows="4"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHandleForm">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 事故详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="事故详情" width="500px">
      <div class="accident-detail" v-if="selectedAccident">
        <div class="detail-item">
          <span class="detail-label">事故ID：</span>
          <span class="detail-value">{{ selectedAccident.accident_id }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">事故类型：</span>
          <span class="detail-value">{{ selectedAccident.accident_type }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">严重程度：</span>
          <span class="detail-value">
            <el-tag :type="getSeverityType(selectedAccident.severity)" effect="dark">
              {{ selectedAccident.severity }}
            </el-tag>
          </span>
        </div>
        <div class="detail-item">
          <span class="detail-label">发生时间：</span>
          <span class="detail-value">{{ selectedAccident.date_time }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">所属高速公路：</span>
          <span class="detail-value">{{ getHighwayName(selectedAccident.highway_code) }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">位置描述：</span>
          <span class="detail-value">{{ selectedAccident.location_desc }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">处理状态：</span>
          <span class="detail-value">
            <el-tag :type="getStatusType(selectedAccident.status)" effect="plain">
              {{ selectedAccident.status }}
            </el-tag>
          </span>
        </div>
        <div class="detail-item" v-if="selectedAccident.HandleMessage">
          <span class="detail-label">处理信息：</span>
          <span class="detail-value">{{ selectedAccident.HandleMessage }}</span>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button
            type="primary"
            @click="openHandleDialog(selectedAccident)"
            v-if="selectedAccident && selectedAccident.status !== '已处理'"
          >
            处理
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, reactive, computed, nextTick, watch } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { Refresh, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import Graphic from '@arcgis/core/Graphic.js'
import Query from '@arcgis/core/rest/support/Query.js'
import gaodeLayer from '../utils/GaoDeBaseLayer'

type AccidentType = {
  accident_id: string
  accident_type: string
  severity: string
  date_time: string
  highway_code: string
  location_desc: string
  status: string
  HandleMessage?: string
  OBJECTID?: number
}

type HandleFormType = {
  accident_id: string
  accident_type: string
  severity: string
  date_time: string
  highway_code: string
  location_desc: string
  status: string
  HandleMessage: string
  OBJECTID?: number
}

let view: MapView | null = null
let highwayLayer: FeatureLayer | null = null
let accidentLayer: FeatureLayer | null = null
let selectedGraphic: Graphic | null = null

// 状态变量
const loading = ref(false)
let accidents: AccidentType[] = []
const highwayList = ref<any[]>([])
const filterStatus = ref('')
const filterSeverity = ref('')
const handleDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const selectedAccident = ref<AccidentType | null>(null)
const handleFormRef = ref<InstanceType<typeof ElForm> | null>(null)
const refreshKey = ref(0)
// 处理表单数据
const handleForm = reactive<HandleFormType>({
  accident_id: '',
  accident_type: '',
  severity: '',
  date_time: '',
  highway_code: '',
  location_desc: '',
  status: '',
  HandleMessage: '',
})

// 处理表单验证规则
const handleFormRules = {
  status: [{ required: true, message: '请选择处理状态', trigger: 'change' }],
  HandleMessage: [{ required: true, message: '请输入处理信息', trigger: 'blur' }],
}
// 折叠面板状态
const isPanelCollapsed = ref(false)

// 切换面板折叠状态
const togglePanel = () => {
  isPanelCollapsed.value = !isPanelCollapsed.value
}
// 获取严重程度对应的标签类型
const getSeverityType = (severity: string) => {
  switch (severity) {
    case '轻微':
      return 'info'
    case '一般':
      return 'warning'
    case '严重':
      return 'danger'
    case '特别严重':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取处理状态对应的标签类型
const getStatusType = (status: string) => {
  switch (status) {
    case '未处理':
      return 'danger'
    case '处理中':
      return 'warning'
    case '已处理':
      return 'success'
    default:
      return 'info'
  }
}

// 获取高速公路名称
const getHighwayName = (highwayCode: string) => {
  const highway = highwayList.value.find((h) => h.attributes.highway_code === highwayCode)
  return highway ? highway.attributes.highway_name : highwayCode
}
watch([filterStatus, filterSeverity], () => {
  refreshAccidentList()
  accidents = accidents.filter((accident) => {
    // 根据处理状态筛选
    if (filterStatus.value && accident.status !== filterStatus.value) {
      return false
    }
    // 根据严重程度筛选
    if (filterSeverity.value && accident.severity !== filterSeverity.value) {
      return false
    }
    return true
  })
  console.log(accidents)
  refreshKey.value++
})
// 刷新事故列表
const refreshAccidentList = async () => {
  if (!accidentLayer) return

  loading.value = true

  try {
    const query = new Query()
    query.where = '1=1'
    query.outFields = ['*']
    query.returnGeometry = true

    const result = await accidentLayer.queryFeatures(query)
    console.log(result.features)
    accidents = result.features.map((feature) => ({
      ...feature.attributes,
    }))
    loading.value = false
    accidents = accidents.filter((accident) => {
      // 根据处理状态筛选
      if (filterStatus.value && accident.status !== filterStatus.value) {
        return false
      }
      // 根据严重程度筛选
      if (filterSeverity.value && accident.severity !== filterSeverity.value) {
        return false
      }
      return true
    })
    nextTick(() => {
      refreshKey.value++
    })
  } catch (error) {
    console.error('加载事故列表失败:', error)
    ElMessage.error('加载事故列表失败')
    loading.value = false
  }
}

// 点击事故列表行
const handleAccidentClick = (row: AccidentType) => {
  selectedAccident.value = row
  detailDialogVisible.value = true
}

// 打开处理对话框
const openHandleDialog = async (accident: AccidentType) => {
  selectedAccident.value = accident
  detailDialogVisible.value = false

  // 填充表单数据
  handleForm.accident_id = accident.accident_id || ''
  handleForm.accident_type = accident.accident_type || ''
  handleForm.severity = accident.severity || ''
  handleForm.date_time = accident.date_time || ''
  handleForm.highway_code = accident.highway_code || ''
  handleForm.location_desc = accident.location_desc || ''
  handleForm.status = accident.status || '未处理'
  handleForm.HandleMessage = accident.HandleMessage || ''
  handleForm.OBJECTID = accident.OBJECTID
  // 根据OBJECTID查找要素并将地图视图中心移动到该位置
  if (accidentLayer) {
    const query = new Query()
    query.where = `OBJECTID = ${accident.OBJECTID}`
    query.outFields = ['*']
    query.returnGeometry = true

    const result = await accidentLayer.queryFeatures(query)
    if (result.features.length > 0) {
      const feature = result.features[0]
      // 将地图视图中心移动到事故点位置
      view?.goTo({
        target: feature.geometry,
        zoom: 15,
      })
    }
  }
  handleDialogVisible.value = true
}

// 提交处理表单
const submitHandleForm = async () => {
  if (!handleFormRef.value) return

  await handleFormRef.value.validate(async (valid) => {
    if (valid) {
      updateAccident()
    }
  })
}

// 更新事故点
const updateAccident = async () => {
  if (!accidentLayer || !selectedAccident.value) return

  try {
    // 查询要更新的图形
    const query = new Query()
    query.where = `OBJECTID = ${handleForm.OBJECTID}`
    query.outFields = ['*']

    const result = await accidentLayer.queryFeatures(query)
    if (result.features.length === 0) {
      ElMessage.error('未找到要更新的事故点')
      return
    }

    // 更新属性
    const updatedGraphic = result.features[0]
    updatedGraphic.attributes.status = handleForm.status
    updatedGraphic.attributes.HandleMessage = handleForm.HandleMessage

    // 提交更新到服务
    const editResult = await accidentLayer.applyEdits({
      updateFeatures: [updatedGraphic],
    })

    if (editResult.updateFeatureResults.length > 0) {
      ElMessage.success('事故处理信息已更新')
      handleDialogVisible.value = false

      // 刷新事故列表
      await refreshAccidentList()
    } else {
      ElMessage.error('更新事故处理信息失败')
    }
  } catch (error) {
    console.error('更新事故处理信息出错:', error)
    ElMessage.error('更新事故处理信息失败')
  }
}

// 加载高速公路列表
const loadHighwayList = async () => {
  if (!highwayLayer) return

  const query = new Query()
  query.where = '1=1'
  query.outFields = ['*']

  try {
    const result = await highwayLayer.queryFeatures(query)
    highwayList.value = result.features
  } catch (error) {
    console.error('加载高速公路列表失败:', error)
    ElMessage.error('加载高速公路列表失败')
  }
}

// 初始化地图
const initMap = async () => {
  try {
    const map = new Map({
      basemap: {
        baseLayers: [gaodeLayer],
      },
    })

    view = new MapView({
      container: 'mapView',
      map: map,
      center: [116.404, 39.915], // 北京中心点坐标
      zoom: 10,
    })

    // 创建高速公路图层
    highwayLayer = new FeatureLayer({
      url: 'https://services.arcgis.com/pPin4rPIRy9xhFS0/arcgis/rest/services/HighwayManagemnetSystem/FeatureServer/0',
      outFields: ['*'],
      popupTemplate: {
        title: '{highway_name}',
        content: [
          {
            type: 'fields',
            fieldInfos: [
              { fieldName: 'highway_code', label: '高速公路编号' },
              { fieldName: 'highway_level', label: '高速公路等级' },
              { fieldName: 'lanes', label: '车道数' },
              { fieldName: 'status', label: '路况状态' },
              { fieldName: 'speed_limit', label: '限速(km/h)' }
            ]
          }
        ]
      },
    })

    // 创建事故点图层
    accidentLayer = new FeatureLayer({
      url: 'https://services.arcgis.com/pPin4rPIRy9xhFS0/arcgis/rest/services/HighwayManagemnetSystem/FeatureServer/1',
      outFields: ['*'],
      popupTemplate: {
        title: '事故点信息',
        content:
          '事故类型：{accident_type}<br>严重程度：{severity}<br>发生时间：{date_time}<br>所属高速公路：{highway_code}<br>位置描述：{location_desc}<br>处理状态：{status}<br>处理信息：{HandleMessage}',
      },
    })

    // 添加图层到地图
    map.add(highwayLayer)
    map.add(accidentLayer)

    // 加载高速公路列表
    await loadHighwayList()

    // 加载事故列表
    await refreshAccidentList()

    // 监听地图点击事件
    view.on('click', async (event) => {
      if (!view || !accidentLayer) return

      // 清除之前的选中状态
      selectedGraphic = null

      // 查询点击位置的事故点
      const query = new Query()
      query.where = '1=1'
      query.outFields = ['*']
      query.returnGeometry = true
      query.geometry = event.mapPoint
      query.spatialRelationship = 'intersects'

      const result = await accidentLayer.queryFeatures(query)
      const graphic = result.features[0]

      if (graphic) {
        selectedGraphic = graphic

        // 显示事故详情
        const attrs = graphic.attributes
        selectedAccident.value = {
          accident_id: attrs.accident_id || '',
          accident_type: attrs.accident_type || '',
          severity: attrs.severity || '',
          date_time: attrs.date_time || '',
          highway_code: attrs.highway_code || '',
          location_desc: attrs.location_desc || '',
          status: attrs.status || '未处理',
          HandleMessage: attrs.HandleMessage || '',
          OBJECTID: attrs.OBJECTID,
        }

        detailDialogVisible.value = true
      }
    })
  } catch (error) {
    console.error('初始化地图失败:', error)
    ElMessage.error('初始化地图失败')
  }
}

onMounted(() => {
  initMap()
})

onUnmounted(() => {
  if (view) {
    view = null
  }
})
</script>

<style scoped>
.map-view {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: #f5f5f5;
}

.accident-panel {
  position: absolute;
  top: 15px;
  left: 15px;
  z-index: 1;
  width: 700px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  border-left: 4px solid #409eff;
  transition: all 0.3s ease;
}

.accident-panel.collapsed {
  width: 40px;
  border-radius: 8px;
}

.collapse-button {
  position: absolute;
  right: -20px;
  top: 50%;
  transform: translateY(-50%);
  width: 40px;
  height: 40px;
  background-color: #409eff;
  color: white;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  z-index: 2;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.collapse-button:hover {
  background-color: #66b1ff;
}

.accident-card {
  border-radius: 8px;
  background-color: #fff;
  border: none;
}

.card-header {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.subtitle {
  margin: 5px 0 0 0;
  font-size: 12px;
  color: #909399;
}

.filter-toolbar {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.accident-detail {
  padding: 10px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
}

.detail-label {
  font-weight: bold;
  width: 120px;
  color: #606266;
}

.detail-value {
  flex: 1;
  color: #303133;
}
</style>
